﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using OpenIddict.Abstractions;
using OpenIddictService.Models;
using System.Security.Claims;
using System.Security.Principal;
using System.Xml.Linq;
using static OpenIddict.Abstractions.OpenIddictConstants;

namespace OpenIddictService.Controllers
{
    public class AccountController : Controller
    {

        UserInfo myuser;
        public AccountController(UserInfo userInfo)
        {
            myuser = userInfo;
        }

        [HttpGet]
        public IActionResult Login(string returnUrl)
        {
            TempData["returnUrl"] = returnUrl;

            return View();
        }

       [HttpPost]
        public async Task<IActionResult> LoginPost(string username, string password)
        {
   
           
            if (username == "admin" && password== "123456")
            {
                myuser.Gid = Guid.NewGuid().ToString();
                myuser.id = 1000L;
                myuser.account = "admin";
                myuser.name = "测试用户";
                myuser.password = "123456";
                myuser.phone = "15928914770";

                var claims = new List<Claim>{
                        new Claim(ClaimTypes.Sid, myuser.id.ToString()),
                        new Claim(ClaimTypes.Name, myuser.account),
                        new Claim(ClaimTypes.NameIdentifier, myuser.id.ToString())
                 };
                var identity = new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
                var authProperties = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTime.UtcNow.AddDays(30)
                };

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(identity),
                    authProperties);

                string url = TempData["returnUrl"].ToString();
                return Redirect(url);

            }
            ModelState.AddModelError(string.Empty, "用户名或者密码错误");
            return View(nameof(Login));

        }
    }
}
